package com.iamteer.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class LoginFilter
 */
public class LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		// 0. 转换
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		// 1. 获取请求资源，截取
		String uri = request.getRequestURI();
		
		// 截取
		uri = uri.substring(uri.lastIndexOf("/") + 1, uri.length());
		
		// 2. 判断，先放行一些资源：/login.jsp、/login
		if ("admin".equals(uri) || "login.jsp".equals(uri)) {
			chain.doFilter(request, response);
		} else {
			// 3. 对其他资源进行拦截
			// 3.1 先获取 Session，获取Session 中的登陆用户（loginInfo）
			HttpSession session = request.getSession(false);
			if (session != null) {
				Object obj = session.getAttribute("loginInfo");
				if (obj != null) {
					// 3.2 如果获取的内容不为空，说明已经登陆，放行
					chain.doFilter(request, response);
				} else {
					// 3.3 如果获取的内容为空，说明没有登陆；跳转到登录
					uri = "/login.jsp";
				}
			} else {
				uri = "login.jsp";
			}
			request.getRequestDispatcher(uri).forward(request, response);
		}
		
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
